package org.mspring.mlog.api.spider.service.impl;

import org.mspring.mlog.api.spider.entity.PublishRule;
import org.mspring.mlog.api.spider.service.PublishRuleService;
import org.mspring.mlog.schedule.SchedulerService;
import org.mspring.mlog.schedule.job.SpiderJob;
import org.mspring.mlog.service.JobService;
import org.mspring.platform.dao.hibernate.GenericDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 
 * @author Gao Youbo
 * @since 2013年7月22日
 */
@Service
@Transactional
public class PublishRuleServiceImpl extends GenericDao<PublishRule, Long> implements PublishRuleService {
    @Autowired
    private SchedulerService schedulerService;
    @Autowired
    private JobService jobService;

    @Override
    public PublishRule createPublishRule(PublishRule rule) {
        // TODO Auto-generated method stub
        if (rule.getJob() == null) {
            return null;
        }
        rule.getJob().setJobClass(SpiderJob.class.getName());
        rule.getJob().setName("内容采集-" + rule.getName());
        rule = save(rule);
        jobService.reloadJobServer(rule.getJob());
        return rule;
    }

    @Override
    public boolean updatePublishRule(PublishRule rule) {
        // TODO Auto-generated method stub
        try {
            if (rule.getJob() == null) {
                return false;
            }
            rule.getJob().setJobClass(SpiderJob.class.getName());
            rule.getJob().setName("内容采集-" + rule.getName());
            update(rule);
            jobService.reloadJobServer(rule.getJob().getId());
            return true;
        } catch (Exception e) {
            // TODO: handle exception
            return false;
        }
    }

    @Override
    public boolean deletePublishRule(Long id) {
        // TODO Auto-generated method stub
        try {
            PublishRule rule = get(id);
            schedulerService.deleteJob(rule.getJob().getId().toString());
            remove(rule);
            return true;
        } catch (Exception e) {
            // TODO: handle exception
            return false;
        }
    }

    @Override
    public PublishRule getByJob(Long jobId) {
        // TODO Auto-generated method stub
        return uniqueResult("select p from PublishRule p where p.job.id = ?", jobId);
    }

    @Override
    public Integer countByRule(Long ruleId) {
        // TODO Auto-generated method stub
        return getHibernateTemplate().count("select count(*) from PublishRule p where p.rule.id = ?", ruleId);
    }
}
